package cn.tedu.yushougeproduct.service.impl;


import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushougeproduct.mapper.CartSkuItemMapper;
import cn.tedu.yushougeproduct.mapper.OrdersMapper;
import cn.tedu.yushougeproduct.mapper.ShoppingCartMapper;
import cn.tedu.yushougeproduct.pojo.entity.Category;
import cn.tedu.yushougeproduct.pojo.entity.Orders;
import cn.tedu.yushougeproduct.pojo.entity.ShoppingCart;
import cn.tedu.yushougeproduct.pojo.param.OrdersAddNewParam;
import cn.tedu.yushougeproduct.pojo.vo.ShoppingCartItemListVO;
import cn.tedu.yushougeproduct.pojo.vo.ShoppingCartStandardVO;
import cn.tedu.yushougeproduct.service.IShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class ShoppingCartServiceImpl implements IShoppingCartService {

    public ShoppingCartServiceImpl() {
        log.info("创建业务对象：ShoppingCartServiceImpl");
    }

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private CartSkuItemMapper cartSkuItemMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public void addNew(Long userId) {

        ShoppingCart shoppingCart = shoppingCartMapper.getByUserId(userId);
        if (shoppingCart == null) {
            // 如果用户没有购物车记录，则创建新的购物车记录
            shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setStateId(1L);
            shoppingCart.setTotalPrice(BigDecimal.ZERO);
            shoppingCart.setGmtCreate(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
            log.debug("根据用户判断购物车不存在，创建新的购物车记录");
            log.debug("完成购物车的添加！");
        } else {
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"该用户已存在一条购物车数据!");
        }
    }


    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除购物车】的业务，参数：{}", id);
        // 检查商品分类是否存在，如果不存在，则抛出异常
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = shoppingCartMapper.deleteById(id);
        if (countById == 0) {
            String message = "删除购物车失败，购物车数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        QueryWrapper<Orders> ordersWrapper = new QueryWrapper<>();
        ordersWrapper.eq("shopping_cat_id", id);
        int countByOrder = ordersMapper.selectCount(ordersWrapper);
        log.debug("根据shopping_cat_id和购物车统计匹配的类别数量，结果：{}", ordersWrapper);
        if (countByOrder > 0) {
            String message = "删除购物车失败！当前购物车仍关联了订单！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        log.debug("从购物车表删除一条数据，完成！");
    }

    @Override
    public void updateShoppingCartState(Long cartId, Long stateId) {
        log.debug("开始处理【根据ID修改购物车状态】的业务，购物车id：{}，状态id：{}", cartId, stateId);
        shoppingCartMapper.updateShoppingCartState(cartId, stateId);

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(cartId);
        shoppingCart.setGmtModified(LocalDateTime.now());
        shoppingCartMapper.updateById(shoppingCart);



        if (stateId == 2) {
            ShoppingCartStandardVO cart = shoppingCartMapper.getStandardById(cartId);
            if (cart != null) {
                Long userId = cart.getUserId();
                List<ShoppingCartItemListVO> cartItems = cartSkuItemMapper.listByCartId(cartId);
                for (ShoppingCartItemListVO cartItem : cartItems) {
                    String orderNumber = generateOrderNumber();
                    Orders orderItem = new Orders();
                    orderItem.setUserId(userId);
                    orderItem.setOrderNumber(orderNumber);
                    orderItem.setProductName(cartItem.getTitle());
                    orderItem.setProductImage(cartItem.getPictures());
                    orderItem.setPrice(cartItem.getPrice());
                    orderItem.setStateId(3L);
                    orderItem.setGmtCreate(LocalDateTime.now());
                    ordersMapper.insert(orderItem);
                    log.debug("生成订单成功，订单号：{}", orderNumber);
                    log.debug("购物车项已复制到订单项:{}",orderItem);
                }

                cartSkuItemMapper.deleteByCartId(cartId);
                log.debug("购物车项已清空");

                int result = shoppingCartMapper.updateCartTotalPrice(cartId);
                log.debug("将新的购物车项数据插入到数据库，完成！影响行数为:{}",result);
            }
        }
    }

    private String generateOrderNumber() {
        LocalDateTime today = LocalDateTime.now();
        String dataPart = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomPart = String.format("%04d", new Random().nextInt(10000));
        String orderNumber = "YSG" + dataPart + randomPart;
        return orderNumber;
    }

    @Override
    public ShoppingCartStandardVO getStandardById(Long cartId) {
        log.debug("开始处理【根据ID查询购物车详情】的业务，参数：{}", cartId);
        ShoppingCartStandardVO queryResult = shoppingCartMapper.getStandardById(cartId);
        if (queryResult == null) {
            String message = "查询购物车详情失败，购物车数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public ShoppingCart getByUserId(Long userId) {
        log.debug("开始处理【根据用户ID查询购物车详情】的业务，参数：{}", userId);
        ShoppingCart queryResult = shoppingCartMapper.getByUserId(userId);
        if (queryResult == null) {
            String message = "查询购物车详情失败，购物车数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }


}
